package controller;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import DAO.BookDetailsDAO;
import DAO.DAOFactory;
import DAO.NotFoundException;
import DAO.UserDAO;

import model.BookDetailsDTO;

@WebServlet("/MakeABookingDateFilter")
public class MakeABookingDateFilter extends HttpServlet {
	private static final long serialVersionUID = 1L;
    	
    public MakeABookingDateFilter() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		  doProcess(request, response) ;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		doProcess(request, response) ;
	}
	
	protected void doProcess(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		//Hardcode bookingID for demo the functions;
		//String bookingID=request.getSession().getAttribute("liuruigege").toString();
		String bookingID="10009";
		System.out.println("bookingIDStr :"+bookingID);
		SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
		
		String fromDate=request.getParameter("fDate");
		if(fromDate=="")
		{
			fromDate=df.format(new Date());
		}
		String toDate=request.getParameter("tDate");
		if(toDate=="")
		{
			toDate=df.format(new Date());
		}
		
		Date fdate = null;
		Date tdate = null;					
		try {
			fdate = df.parse(fromDate);
			tdate = df.parse(toDate);
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		
		String emergency1=request.getParameter("emergencyvalue");		
		String emergency=null;
		if(request.getParameter("emergencyvalue")!=null)
		{
			emergency=request.getParameter("emergencyvalue");
		}
		else{
			emergency="N";
		}

		String priority1 = request.getParameter("priorityvalue");
		String priority = "";
		System.out.println("before enter if");
		System.out.println(priority1.equals("Low"));
		if(priority1.equals("High"))
		 {
			 priority="1".toString();
		 }
		 else if(priority1=="Medium")
			{priority="2".toString();}	
		 else
		 {
			 priority="3".toString();
		 }


		String fromDate1=df.format(fdate);
		String toDate1=df.format(tdate);
		String reason;
		if(request.getParameter("reasonvalue")!=null)
		{
			reason=request.getParameter("reasonvalue");
		}
		else
		{
			reason="";
		}
		
		String facilityName;
		if(request.getParameter("facName")!=null)
		{
		   facilityName=request.getParameter("facName");
		}
		else
		{
			facilityName="1-5";
		}
		//String facilityName=request.getParameter("facName");
		
		String bookedOn=df.format(new Date());
		int bookedBy=10000003;
		String status="Update";
		int modifiedBy=10000003;
		String modifiedOn=df.format(new Date());
		String comment=null;
		
		request.setAttribute("emergency", emergency);
		request.setAttribute("priority", priority);
		request.setAttribute("fromDate", fromDate1);
		request.setAttribute("toDate", toDate1);
		request.setAttribute("reason", reason);
		request.setAttribute("facilityName", facilityName);
		request.setAttribute("bookedOn", bookedOn);
		request.setAttribute("bookedBy", bookedBy);
		request.setAttribute("status", status);
		request.setAttribute("modifiedBy", modifiedBy);
		request.setAttribute("modifiedOn", modifiedOn);
		request.setAttribute("comment", comment);
				
		ArrayList<BookDetailsDTO> allBooking=new ArrayList<BookDetailsDTO>();		
		BookDetailsDAO bd=DAOFactory.loadInstance().getBookDetailsDAO();
//		HttpSession session = request.getSession();
//		
//		session.setAttribute("emergencyc", emergency);		
//		session.setAttribute("priorityc", priority);
//		session.setAttribute("fromDate1c", fromDate1);
//		session.setAttribute("toDate1c", toDate1);
//		session.setAttribute("reasonc",reason);
//		session.setAttribute("facilityNamec", facilityName);
//		session.setAttribute("bookedOnc", bookedOn);
	
		try {
			System.out.println("TELL ME WHY");	
			allBooking=bd.findAll();
			request.setAttribute("allbookings", allBooking);
		} catch (NotFoundException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		
		RequestDispatcher rd = null;
		
		String Approve="Approve";
//		if(facilityName!=nu
		 System.out.println(allBooking.size());
			for(int i=0;i<allBooking.size();i++)
			{
				Date fdateOLD = null;
				Date tdateOLD = null;
							
				SimpleDateFormat df1=new SimpleDateFormat("yyyy-MM-dd");
				
				try {
					fdateOLD = df1.parse(allBooking.get(i).getFromDate().toString());

					tdateOLD = df1.parse(allBooking.get(i).getToDate().toString());

				} catch (ParseException e1) {

					e1.printStackTrace();
				}
				 
				System.out.println(allBooking.get(i).getBookingID());
				if(!(allBooking.get(i).getFacilityName().equals(facilityName)))
				{
					 System.out.println(i);
					 System.out.println(facilityName);
					 System.out.println(allBooking.get(i).getFacilityName());
					 
					 rd=request.getRequestDispatcher("/BookingInProcess.jsp");						
				}
				else
				{	//fdate tdate fdateOLD tdateOLD fdate tdate				
				    // if(fdateOLD.after(tdate) || tdateOLD.before(fdate))
					 //if(!fdateOLD.before(tdate) || !tdateOLD.after(fdate))
					
					   System.out.println("Same name" +fdate+" "+tdate);
					   System.out.println("OLD"+fdateOLD+" "+tdateOLD);
					   
					   //if(tdate.compareTo(fdateOLD)<0 || tdateOLD.compareTo(fdate)<0)
					   
				   if((tdate.compareTo(fdateOLD)<0 && fdate.compareTo(fdateOLD)<0)
						|| (fdate.compareTo(tdateOLD)>0 && tdate.compareTo(tdateOLD)>0))
				   {
					    System.out.println("Date ");
					    rd=request.getRequestDispatcher("/MakeABooking.jsp");						    
				   }

				   else if(!(allBooking.get(i).getStatus().equals(Approve)))
				   {
					  System.out.println("Status ");
					  rd=request.getRequestDispatcher("/MakeABooking.jsp");	
				   }
				   else
				   {  System.out.println("ERROR ");
					  request.setAttribute("Message", "Your booking is conflicting; Please choose another date.");
				      rd=request.getRequestDispatcher("/UpdateBooking.jsp");	
				      break;
				   }
			   }
			}
//			String bookingIdStr=request.getSession().getAttribute("bookingID").toString();
//			int bookingID=Integer.parseInt(bookingIdStr);
		
//			int bookingID=Integer.parseInt(bookingIDStr);
			
			System.out.println("bookingID:"+bookingID);
			System.out.println("emergency:"+ emergency);
			System.out.println("priority:"+ priority);
			System.out.println("fromDate:"+ fromDate1);
			System.out.println("toDate:"+ toDate1);
			System.out.println("reason:"+ reason);
			System.out.println("facilityName:"+ facilityName);
			System.out.println("bookedOn:"+ bookedOn);
			System.out.println("bookedBy:"+ bookedBy);
			System.out.println("status:"+ status);
			System.out.println("modifiedBy:"+ modifiedBy);
			System.out.println("modifiedOn:"+ modifiedOn);
			System.out.println("comment:"+ comment);
			try {
				bd.update(Integer.valueOf(bookingID), emergency, priority, fromDate1, toDate1, reason, facilityName,
						bookedOn, bookedBy, status, modifiedBy, modifiedOn, comment);
			} catch (NotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			//if emergency, send email:
			if (emergency.equals("Y")){
				UserDAO uDAO=DAOFactory.loadInstance().getUserDAO();
				String toAddress="";
				try {
					toAddress=uDAO.findManagerEmail(bookedBy);
					System.out.println(toAddress);
				} catch (NotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				String subject="A New Emergency Booking Waiting For Your Approval";
				String content="There is a new emergency booking waiting for your approval within " +
						"3 hours; Otherwise the system will *APPROVE* it automatically. Please DON'T " +
						"reply to this email as it's auto-generated";
				EmailController email=new EmailController();
				email.SendEmail(toAddress, subject, content);
			}
			//request.getSession().removeAttribute("liurui");
			rd.forward(request, response);

	}

}
